package com.cortex.papaya.search;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.carrot2.core.Document;
import org.carrot2.source.SearchEngineResponse;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.util.Log;

import com.cortex.papaya.utilities.MyLog;

/**
 * @author Gal lavie
 * this class make search in carrot2 engine by IQuerySearch interface.
 * the search run in new thread.
 * after arrived all results the class order the results by category and 
 * send message to PapayaApplication with results
 * 
 *
 */

public class FetchData {
	private OnStateDataChanged changedState;
	private IQuerySearch querySearch;
	private StartSearchThread startSearchThread;

	public IQuerySearch getQuerySearch() {
		return querySearch;
	}
	public void setQuerySearch(IQuerySearch querySearch) {
		this.querySearch = querySearch;
	}
	public void setDataLoadedListener(OnStateDataChanged changedState){
		this.changedState = changedState;
	}
	public interface OnStateDataChanged{
		void timeLoadDataStarted();
		void timeLoadDataFinished(List<Document> documents);
		void timeLoadDataCanceled(String message);
	}
	public void startFetching(){
		if(querySearch != null){
			startSearchThread = new StartSearchThread();
			startSearchThread.execute();
		}
	}
	public void cancelFetching(){
		if(startSearchThread !=null){
			startSearchThread.cancel(true);
		}
	}
	public boolean isFetchRunning(){
		boolean retValue = false;
		if(startSearchThread != null){
			retValue = startSearchThread.getStatus() == Status.RUNNING;
		}
		return retValue;
	}
	private class StartSearchThread extends AsyncTask<Void, String, List<Document>>{

		@Override
		protected List<Document> doInBackground(Void... params) {
			SearchEngineResponse response = null;
			try {
				response = querySearch.run();
			} catch (Exception e) {
				publishProgress("you have a problem with search");
			}
			return response.results;
		}
		@Override
		protected void onPreExecute() {
			if(changedState != null){
				changedState.timeLoadDataStarted();
			}
		}
		@Override
		protected void onProgressUpdate(String... values) {
			if(changedState != null){
				changedState.timeLoadDataCanceled(values[0]);
			}
		}
		@Override
		protected void onPostExecute(List<Document> result) {
			if(changedState != null){
				changedState.timeLoadDataFinished(result);
			}
		}
		@Override
		protected void onCancelled() {
			super.onCancelled();
			if(changedState != null){
				changedState.timeLoadDataCanceled("search canceled");
			}
		}

	}
}
